package com.loveprogrammer.factory;

import com.alibaba.fastjson2.JSONArray;
import com.loveprogrammer.engine.enums.EquipmentEnum;
import com.loveprogrammer.engine.enums.QualityEnum;
import com.loveprogrammer.engine.enums.WeaponTypeEnum;
import com.loveprogrammer.factory.template.EquipmentTemplate;
import com.loveprogrammer.model.Monster;
import com.loveprogrammer.model.goods.Equipment;
import com.loveprogrammer.model.goods.Weapon;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @description: 装备工厂
 * @author: eric
 * @date: 2023-02-23 10:34
 **/
public class EquipmentFactory {

    private static List<EquipmentTemplate> allEquipmentTemplates;
    private static List<EquipmentTemplate> weaponTemplates;
    private static Map<Integer,EquipmentTemplate> weaponTemplateIdMap;


    static {
        try {
            // 读取配置文件，然后加载到weaponTemplates中
            ClassLoader classLoader = EquipmentFactory.class.getClassLoader();

            InputStream inputStream = classLoader.getResourceAsStream("template/equipments/weapon.json");

            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            weaponTemplates = JSONArray.parseArray(responseStrBuilder.toString(),EquipmentTemplate.class);
            weaponTemplateIdMap = weaponTemplates.stream().collect(Collectors.toMap(EquipmentTemplate::getId, e->e));


            if(allEquipmentTemplates == null){
                allEquipmentTemplates = new ArrayList<>();
            }
            allEquipmentTemplates.addAll(weaponTemplates);

            // 加载其他的普通装备
            String path = classLoader.getResource("template/equipments").getFile();//注意getResource("")里面是空字符串
            File file = new File(path);
            File[] files = file.listFiles();
            for (File f : files) {
                if(f.getName().equals("weapon.json")){
                    continue;
                }
                String fileName = "template/equipments/" + f.getName();
                inputStream = classLoader.getResourceAsStream(fileName);

                streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                responseStrBuilder = new StringBuilder();

                String str;
                while ((str = streamReader.readLine()) != null)
                    responseStrBuilder.append(str);

                List<EquipmentTemplate> equipmentTemplates = JSONArray.parseArray(responseStrBuilder.toString(),EquipmentTemplate.class);
                allEquipmentTemplates.addAll(equipmentTemplates);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static List<EquipmentTemplate> getWeaponTemplates() {
        return weaponTemplates;
    }

    public static Equipment createEquipment(Monster monster,
                                            QualityEnum qualityEnum){
        Equipment result;
        // 根据怪物等级，找到对应的装备; 去掉等级过高的装备
        List<EquipmentTemplate> templates = allEquipmentTemplates.stream().filter(e -> e.getLevel() <= monster.getLevel()).collect(Collectors.toList());

        // 随机找到一个装备模板
        EquipmentTemplate equipmentTemplate = templates.get(new Random().nextInt(templates.size()));
        // 找到装备的品质
        if(equipmentTemplate.getType().equalsIgnoreCase(EquipmentEnum.WEAPON.getCode())){
            result = getWeapon(equipmentTemplate,qualityEnum);
        }else{
            // 不是武器的话都一样
            result = getOtherEquipment(equipmentTemplate,qualityEnum);
        }
        // 添加词缀
        return result;
    }

    private static Weapon getWeapon(EquipmentTemplate equipmentTemplate, QualityEnum qualityEnum) {
        Weapon weapon = new Weapon(equipmentTemplate.getName(),equipmentTemplate.getType(),
                equipmentTemplate.getDesc(), EquipmentEnum.WEAPON,
                WeaponTypeEnum.getByCode(equipmentTemplate.getWeaponType()),qualityEnum,equipmentTemplate.getId());
        // 品质越高，浮动越小
        weapon.setGoods_id(equipmentTemplate.getId());
        weapon.setLevel(equipmentTemplate.getLevel());
        weapon.setArmature(calculate(equipmentTemplate.getArmature(),qualityEnum));
        weapon.setStrength(calculate(equipmentTemplate.getStrength(),qualityEnum));
        weapon.setSpeed(calculate(equipmentTemplate.getSpeed(),qualityEnum));
        weapon.setConstitution(calculate(equipmentTemplate.getConstitution(),qualityEnum));
        weapon.setTechnique(calculate(equipmentTemplate.getTechnique(),qualityEnum));
        weapon.setHp(calculate(equipmentTemplate.getHp(),qualityEnum));
        weapon.setMagic(calculate(equipmentTemplate.getMagic(),qualityEnum));
        weapon.setSpeed(calculate(equipmentTemplate.getSpeed(),qualityEnum));
        weapon.setEvasion(calculate(equipmentTemplate.getEvasion(),qualityEnum));
        weapon.setFortune(calculate(equipmentTemplate.getFortune(),qualityEnum));
        weapon.setPoisonResistance(calculate(equipmentTemplate.getPoisonResistance(),qualityEnum));
        weapon.setFlameResistance(calculate(equipmentTemplate.getFlameResistance(),qualityEnum));
        weapon.setThunderResistance(calculate(equipmentTemplate.getThunderResistance(),qualityEnum));
        weapon.setIceResistance(calculate(equipmentTemplate.getIceResistance(),qualityEnum));
        return weapon;
    }


    public static Equipment getOtherEquipment(EquipmentTemplate equipmentTemplate, QualityEnum qualityEnum) {
        Equipment equipment = new Equipment(equipmentTemplate.getName(),equipmentTemplate.getType(),
                equipmentTemplate.getDesc(),EquipmentEnum.getByCode(equipmentTemplate.getType()),qualityEnum,equipmentTemplate.getId());
        // 品质越高，浮动越小
        equipment.setGoods_id(equipmentTemplate.getId());
        equipment.setLevel(equipmentTemplate.getLevel());
        equipment.setArmature(calculate(equipmentTemplate.getArmature(),qualityEnum));
        equipment.setStrength(calculate(equipmentTemplate.getStrength(),qualityEnum));
        equipment.setSpeed(calculate(equipmentTemplate.getSpeed(),qualityEnum));
        equipment.setConstitution(calculate(equipmentTemplate.getConstitution(),qualityEnum));
        equipment.setTechnique(calculate(equipmentTemplate.getTechnique(),qualityEnum));
        equipment.setHp(calculate(equipmentTemplate.getHp(),qualityEnum));
        equipment.setMagic(calculate(equipmentTemplate.getMagic(),qualityEnum));
        equipment.setSpeed(calculate(equipmentTemplate.getSpeed(),qualityEnum));
        equipment.setEvasion(calculate(equipmentTemplate.getEvasion(),qualityEnum));
        equipment.setFortune(calculate(equipmentTemplate.getFortune(),qualityEnum));
        // 四种元素的抗性
        equipment.setPoisonResistance(calculate(equipmentTemplate.getPoisonResistance(),qualityEnum));
        equipment.setFlameResistance(calculate(equipmentTemplate.getFlameResistance(),qualityEnum));
        equipment.setThunderResistance(calculate(equipmentTemplate.getThunderResistance(),qualityEnum));
        equipment.setIceResistance(calculate(equipmentTemplate.getIceResistance(),qualityEnum));
        return equipment;
    }

    private static int calculate(String data, QualityEnum qualityEnum) {
        if(StringUtils.isEmpty(data)){
            return 0;
        }
        String[] split = data.split("-");
        int min = Integer.parseInt(split[0]);
        int max = Integer.parseInt(split[1]);
        int add = max - min;
        if(add > 1){
            switch (qualityEnum){
                case 黄色:
                    min = min + add/5;
                    break;
                case 紫色:
                    min = min + add/4;
                    break;
                case 红色:
                    min = min + add/3;
                    break;
                case 暗金:
                    min = min + add/2;
                    break;
                default:
                    break;
            }
        }
        if(max > min) {
            // 根据品质改变最大最小值
            return min + new Random().nextInt(max - min);
        }else if (max == min){
            return max;
        }
        return 0;
    }

    public static void main(String[] args) {
//        for (EquipmentTemplate template : allEquipmentTemplates) {
//            System.out.println(template.toString());
//        }

        Equipment equipment = createEquipment(MonsterFactory.createMonster(101, 10), QualityEnum.白色);
        System.out.println("获得装备");
        System.out.println(equipment.prettyPrint());

    }

}
